<template>
  <div class="container bg-white">
    <blank
      :value="showEmpty"
      :title="empty.title"
      :message="empty.message"
      :icon="empty.icon"
    />
    <van-loading
      size="24px"
      vertical
      v-if="authenting"
    >等待微信授权结果...</van-loading>
    <van-button
      type="default"
      icon="bulb-o"
      size="small"
      v-if="debug"
      @click="showPopup"
    >DEBUG</van-button>
    <van-popup
      v-model="showDebug"
      class="debug"
      position="bottom"
      closeable
      close-icon-position="bottom-left"
      :style="{ height: '100%' }"
    >
      <h1>微信授权调试信息</h1>
      <json-viewer
        :value="debug"
        :expand-depth=5
        copyable
        sort
      />
    </van-popup>
  </div>
</template>

<script>
import JsonViewer from 'vue-json-viewer'
import Blank from '@/components/abnor/blank'
import { Loading, Button, Popup } from 'vant'

export default {
  name: 'WechatAuth',
  components: {
    JsonViewer,
    Blank,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Loading.name]: Loading
  },
  data () {
    return {
      showEmpty: false,
      authenting: true,
      empty: {
        title: '微信授权失败',
        message: '抱歉，当前微信授权失败...',
        icon: '/static/icons/blank_authent.png'
      },
      showDebug: false,
      webAuthData: null,
      params: null,
      connectId: 0
    }
  },
  computed: {
    debug () {
      if (
        process.env.NODE_ENV === 'development' ||
        process.env.NODE_ENV === 'production'
      ) {
        return {
          webAuthData: this.webAuthData,
          params: this.params
        }
      }
      return false
    }
  },
  created () {
    this.params = {
      id: sessionStorage.getItem('wxUserInfo')
    }
    this.onAuthent(this.params)
  },
  methods: {
    onAuthent (params) {
      this.$http.base
        .wechatUserInfo(params)
        .then(res => {
          let data = res.data
          this.webAuthData = data
          this.authenting = false
          this.empty = {
            title: '微信授权成功',
            message: '成功...',
            icon: '/static/icons/blank_authent.png'
          }
          this.showEmpty = true
        })
        .catch(err => {
          console.log(err)
          this.empty.message = err
          this.authenting = false
          this.showEmpty = true
        })
    },
    showPopup () {
      this.showDebug = true
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.van-loading {
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.van-popup {
  h1 {
    margin: 0;
    font-size: 14px;
    padding: 15px;
    border-bottom: 1px solid #f2f2f2;
  }
}
.van-button {
  position: fixed;
  right: 2px;
  bottom: 2px;
}
</style>
